package br.ufrj.ppgi.jemf_basic_example.fragments;

import java.util.ArrayList;
import java.util.Random;

import android.app.Fragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.Toast;
import br.ufrj.ppgi.jemf.core.coordination.AbstractUser;
import br.ufrj.ppgi.jemf.mobile.FeatureHolder.EnumFeatureType;
import br.ufrj.ppgi.jemf.mobile.bean.Commander;
import br.ufrj.ppgi.jemf.mobile.bean.Medical;
import br.ufrj.ppgi.jemf.mobile.bean.Responder;
import br.ufrj.ppgi.jemf.mobile.bean.Team;
import br.ufrj.ppgi.jemf.mobile.bean.Volunteer;
import br.ufrj.ppgi.jemf.mobile.factory.EmergencyManagementFactory;
import br.ufrj.ppgi.jemf_basic_example.R;

public class TeamFragment extends Fragment implements OnClickListener, OnItemClickListener, OnItemLongClickListener {

	// JEMF.
	EmergencyManagementFactory emf;
	// Loader.
    private LoaderCallbacks<Cursor> loaderCall = null;
    // Loader ID.
	private final int loaderID = 17;
	// Users.
	private Commander commander;
	private Responder responder;
	private Medical medical;
	private Volunteer volunteer, volunteer2;



	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Instantiating JEMF.
		emf = EmergencyManagementFactory.newInstance(this.getActivity().getApplicationContext());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_team, container, false);

		// Button Add Team.
		Button button = (Button) rootView.findViewById(R.id.buttonTEAM);
		button.setOnClickListener(this);

		// Team List.
		ListView listView = (ListView) rootView.findViewById(R.id.listViewTEAM);
		listView.setOnItemClickListener(this);
		listView.setOnItemLongClickListener(this);

		// Instantiating a Cursor Adapter to set in List View.
		CursorAdapter cursorAdapter = emf.getMainFactory(EnumFeatureType.TEAM).getAdapter();
		listView.setAdapter(cursorAdapter);

		return rootView;
	}

	@Override
	public void onResume() {
		// Instantiating a Loader to read data from database.
		this.loaderCall = emf.getMainFactory(EnumFeatureType.TEAM).getLoader(null, null, null);
		// Loading content.
		// Prepare the loader. Either re-connect with an existing one, or start a new one.
		if (getLoaderManager().getLoader(loaderID) != null && !getLoaderManager().getLoader(this.loaderID).isReset()) {
			this.getActivity().getLoaderManager().restartLoader(this.loaderID, null, this.loaderCall);
		} else {
			this.getActivity().getLoaderManager().initLoader(this.loaderID, null, this.loaderCall);
		}
		super.onResume();
	}

	@Override
	public void onClick(View arg0) {
		// Get Users.
		this.getUsers();
		// Checking temporary members.
        if (commander == null) {
            Toast.makeText(this.getActivity().getApplicationContext(), "Register a Commader, please.", Toast.LENGTH_SHORT).show();
            return;
        }
        if (responder == null) {
            Toast.makeText(this.getActivity().getApplicationContext(), "Register a Responder, please.", Toast.LENGTH_SHORT).show();
            return;
        }
        if (medical == null) {
            Toast.makeText(this.getActivity().getApplicationContext(), "Register a Medical, please.", Toast.LENGTH_SHORT).show();
            return;
        }
        if (volunteer == null) {
            Toast.makeText(this.getActivity().getApplicationContext(), "Register a Volunteer, please.", Toast.LENGTH_SHORT).show();
            return;
        }

		Random r = new Random();
		// Members.
        ArrayList<AbstractUser> members = new ArrayList<AbstractUser>();
        members.add(responder);
    	members.add(medical);
    	members.add(volunteer);
		// Creating Random Team.
        Team team = new Team(commander, members);
        team.setName("Team " + String.valueOf(r.nextInt()));
		// Saving Team.
		emf.getMainFactory(EnumFeatureType.TEAM).getManager().save(team);
        Toast.makeText(this.getActivity().getApplicationContext(), team.toString(), Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
	    Cursor cursor = (Cursor) arg0.getAdapter().getItem(arg2);
	    if (cursor != null) {
			// Members.
	        ArrayList<AbstractUser> members = new ArrayList<AbstractUser>();
	        members.add(responder);
	        members.add(medical);
	        members.add(volunteer);
	        if (volunteer2 != null) {
	        	members.add(volunteer2);
	        }

	        // Updating Team.
	        Random r = new Random();
	        Team team = emf.getMainFactory(EnumFeatureType.TEAM).getManager().deserialize(cursor);
	        team.setName("Team " + String.valueOf(r.nextInt()));
	        team.setLeader(commander);
	        team.setMembers(members);
			// Saving Team.
			emf.getMainFactory(EnumFeatureType.TEAM).getManager().save(team);
	        Toast.makeText(this.getActivity().getApplicationContext(), team.toString(), Toast.LENGTH_SHORT).show();
	    }
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
	    Cursor cursor = (Cursor) arg0.getAdapter().getItem(arg2);
	    if (cursor != null) {
			// Deleting Team.
	        Team team = emf.getMainFactory(EnumFeatureType.TEAM).getManager().deserialize(cursor);
			emf.getMainFactory(EnumFeatureType.TEAM).getManager().remove(team);
	    }
		return true;
	}

	private void getUsers() {
		Random r = new Random();

		// Commander.
        // Loading a random commander.
		ArrayList<Commander> commanders = emf.getMainFactory(EnumFeatureType.COMMANDER).getManager().loadAll(null, null, null, null);
        if ((commanders != null) && (commanders.size() > 0)) {
        	commander = commanders.get(r.nextInt(commanders.size()));
        }

		// Responder.
        // Loading a random responder.
		ArrayList<Responder> responders = emf.getMainFactory(EnumFeatureType.RESPONDER).getManager().loadAll(null, null, null, null);
        if ((responders != null) && (responders.size() > 0)) {
        	responder = responders.get(r.nextInt(responders.size()));
        }

		// Medical.
        // Loading a random medical.
		ArrayList<Medical> medicals = emf.getMainFactory(EnumFeatureType.MEDICAL).getManager().loadAll(null, null, null, null);
        if ((medicals != null) && (medicals.size() > 0)) {
        	medical = medicals.get(r.nextInt(medicals.size()));
        }

		// Volunteer.
        // Loading a random volunteer.
		ArrayList<Volunteer> volunteers = emf.getMainFactory(EnumFeatureType.VOLUNTEER).getManager().loadAll(null, null, null, null);
        if ((volunteers != null) && (volunteers.size() > 0)) {
        	volunteer = volunteers.get(r.nextInt(volunteers.size()));
        }

		// Volunteer 2.
        // Loading a random volunteer.
        if ((volunteers != null) && (volunteers.size() > 1)) {
        	volunteers.remove(volunteer);
        	volunteer2 = volunteers.get(r.nextInt(volunteers.size()));
        }
	}

}
